<template>
  <div class="flex-list" :style="listStyle">
    <div
      v-for="(item, index) of dataList"
      :key="index"
      :style="itemStyle"
      class="flex-list-item"
      @click="onSelect(item)"
    >
      <slot :data="item" :index="index" :active="selectedList.indexOf(item.type) >= 0" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'flex-list',
  emits: ['change'],
  props: {
    value: { type: Array, default: () => [] },
    dataList: { type: Array, default: () => [] },
    listStyle: { type: Object, default: () => ({}) },
    itemStyle: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      selectedList: [],
    };
  },
  computed: {
    dataTypeList() {
      return this.dataList.map((item) => item.type);
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(list) {
        this.selectedList = list;
      },
    },
  },
  methods: {
    onSelect(data = {}) {
      const { type } = data;
      const selectedList = this.selectedList.splice(0);
      const index = selectedList.indexOf(type);
      const selected = index >= 0;
      if (selected) {
        selectedList.splice(index, 1);
      } else {
        selectedList.push(type);
      }
      selectedList.sort((prev, next) => {
        return this.dataTypeList.indexOf(prev) - this.dataTypeList.indexOf(next);
      });
      this.selectedList = selectedList;
      this.$emit('update:modelValue', selectedList);
      this.$nextTick(() => {
        this.$emit('change', {
          data: data,
          selected: !selected,
          selectedList: selectedList,
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
.flex-list {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
</style>
